<template>
  <el-dialog
    :model-value="visible"
    @update:model-value="$emit('update:visible', $event)"
    :title="dialogTitle"
    width="600px"
    :close-on-click-modal="false"
    @close="handleClose"
    :fullscreen="isMobile"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
      size="large"
    >
      <!-- 基本信息 -->
      <el-form-item label="标题" prop="title">
        <el-input
          v-model="form.title"
          placeholder="请输入日程标题"
          maxlength="100"
          show-word-limit
        />
      </el-form-item>

      <el-form-item label="描述" prop="description">
        <el-input
          v-model="form.description"
          type="textarea"
          :rows="3"
          placeholder="请输入日程描述（可选）"
          maxlength="500"
          show-word-limit
        />
      </el-form-item>

      <!-- 时间设置 -->
      <el-form-item label="开始时间" prop="start_time">
        <el-date-picker
          v-model="form.start_time"
          type="datetime"
          placeholder="选择开始时间"
          format="YYYY-MM-DD HH:mm"
          value-format="YYYY-MM-DD HH:mm:ss"
          style="width: 100%"
        />
      </el-form-item>

      <el-form-item label="结束时间" prop="end_time">
        <el-date-picker
          v-model="form.end_time"
          type="datetime"
          placeholder="选择结束时间"
          format="YYYY-MM-DD HH:mm"
          value-format="YYYY-MM-DD HH:mm:ss"
          style="width: 100%"
        />
      </el-form-item>

      <!-- 位置和分类 -->
      <el-form-item label="地点" prop="location">
        <el-input
          v-model="form.location"
          placeholder="请输入地点（可选）"
          maxlength="100"
          show-word-limit
        />
      </el-form-item>

      <el-form-item label="分类" prop="category">
        <el-select
          v-model="form.category"
          placeholder="请选择分类（可选）"
          clearable
          style="width: 100%"
        >
          <el-option label="工作" value="work" />
          <el-option label="个人" value="personal" />
          <el-option label="学习" value="study" />
          <el-option label="会议" value="meeting" />
          <el-option label="娱乐" value="entertainment" />
          <el-option label="其他" value="other" />
        </el-select>
      </el-form-item>

      <!-- 优先级和状态 -->
      <el-form-item label="优先级" prop="priority">
        <el-radio-group v-model="form.priority">
          <el-radio value="low">低</el-radio>
          <el-radio value="medium">中</el-radio>
          <el-radio value="high">高</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item v-if="mode === 'edit'" label="状态" prop="status">
        <el-select
          v-model="form.status"
          placeholder="请选择状态"
          style="width: 100%"
        >
          <el-option label="待处理" value="pending" />
          <el-option label="进行中" value="in-progress" />
          <el-option label="已完成" value="completed" />
          <el-option label="已取消" value="cancelled" />
        </el-select>
      </el-form-item>

      <!-- 提醒设置 -->
      <el-form-item label="提醒" prop="reminder">
        <el-switch
          v-model="form.reminder"
          active-text="开启"
          inactive-text="关闭"
        />
      </el-form-item>

      <el-form-item
        v-if="form.reminder"
        label="提醒时间"
        prop="reminderTime"
      >
        <el-date-picker
          v-model="form.reminderTime"
          type="datetime"
          placeholder="选择提醒时间"
          format="YYYY-MM-DD HH:mm"
          value-format="YYYY-MM-DD HH:mm:ss"
          style="width: 100%"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="loading">
          {{ mode === 'create' ? '创建' : '更新' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted, onUnmounted } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { useScheduleStore } from '@/stores/schedule'
import type { ScheduleResponse, ScheduleCreate, ScheduleUpdate } from '@/api/models'

interface Props {
  visible: boolean
  schedule?: ScheduleResponse | null
  mode: 'create' | 'edit'
  defaultDate?: string // YYYY-MM-DD 格式的日期字符串
}

interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'success'): void
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  schedule: null,
  mode: 'create',
  defaultDate: undefined
})

const emit = defineEmits<Emits>()

const scheduleStore = useScheduleStore()

// 响应式数据
const formRef = ref<FormInstance>()
const loading = ref(false)

// 对话框标题
const dialogTitle = computed(() => {
  return props.mode === 'create' ? '新建日程' : '编辑日程'
})

// 表单数据
const form = ref({
  title: '',
  description: '',
  start_time: '',
  end_time: '',
  location: '',
  category: '',
  priority: 'medium' as 'low' | 'medium' | 'high',
  status: 'pending' as 'pending' | 'in-progress' | 'completed' | 'cancelled',
  reminder: false,
  reminderTime: ''
})

// 表单验证规则
const rules: FormRules = {
  title: [
    { required: true, message: '请输入日程标题', trigger: 'blur' },
    { min: 1, max: 100, message: '标题长度在 1 到 100 个字符', trigger: 'blur' }
  ],
  start_time: [
    { required: true, message: '请选择开始时间', trigger: 'change' }
  ],
  end_time: [
    { required: true, message: '请选择结束时间', trigger: 'change' }
  ],
  priority: [
    { required: true, message: '请选择优先级', trigger: 'change' }
  ],
  reminderTime: [
    { required: true, message: '请选择提醒时间', trigger: 'change' }
  ]
}

// 监听props变化，初始化表单数据
watch(() => props.visible, (newVal) => {
  if (newVal && props.schedule) {
    // 编辑模式，填充表单数据
    form.value = {
      title: props.schedule.title,
      description: props.schedule.description || '',
      start_time: props.schedule.start_time,
      end_time: props.schedule.end_time,
      location: '',
      category: '',
      priority: props.schedule.priority === 'urgent' ? 'high' : props.schedule.priority || 'medium',
      status: props.schedule.status === 'in_progress' ? 'in-progress' : props.schedule.status || 'pending',
      reminder: props.schedule.is_reminder_enabled || false,
      reminderTime: props.schedule.reminder_minutes ? new Date(new Date(props.schedule.start_time).getTime() - props.schedule.reminder_minutes * 60000).toISOString().slice(0, 19).replace('T', ' ') : ''
    }
  } else if (newVal) {
    // 创建模式，重置表单数据
    resetForm()
  }
})

// 监听提醒开关，自动设置提醒时间
watch(() => form.value.reminder, (newVal) => {
  if (newVal && !form.value.reminderTime) {
    // 默认提醒时间为开始时间前15分钟
    const startTime = new Date(form.value.start_time)
    startTime.setMinutes(startTime.getMinutes() - 15)
    form.value.reminderTime = startTime.toISOString().slice(0, 19).replace('T', ' ')
  }
})

// 响应式状态
const isMobile = ref(window.innerWidth <= 768)

// 监听窗口大小变化
const handleResize = () => {
  isMobile.value = window.innerWidth <= 768
}

// 组件挂载时添加监听
onMounted(() => {
  window.addEventListener('resize', handleResize)
})

// 组件卸载时移除监听
onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
})

// 获取指定日期的开始和结束时间
const getDateTime = (dateString?: string) => {
  let targetDate: Date
  
  if (dateString) {
    // 如果传入了日期字符串，使用该日期
    const [year, month, day] = dateString.split('-').map(Number)
    targetDate = new Date(year, month - 1, day)
  } else {
    // 否则使用当前日期
    targetDate = new Date()
  }
  
  const year = targetDate.getFullYear()
  const month = String(targetDate.getMonth() + 1).padStart(2, '0')
  const day = String(targetDate.getDate()).padStart(2, '0')
  
  // 开始时间：目标日期的 9:00
  const startTime = `${year}-${month}-${day} 09:00:00`
  
  // 结束时间：目标日期的 18:00
  const endTime = `${year}-${month}-${day} 18:00:00`
  
  return { startTime, endTime }
}

// 重置表单
const resetForm = () => {
  const { startTime, endTime } = getDateTime(props.defaultDate)
  
  form.value = {
    title: '',
    description: '',
    start_time: startTime,
    end_time: endTime,
    location: '',
    category: '',
    priority: 'medium',
    status: 'pending',
    reminder: false,
    reminderTime: ''
  }
  formRef.value?.clearValidate()
}

// 关闭对话框
const handleClose = () => {
  emit('update:visible', false)
  resetForm()
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    // 验证表单
    await formRef.value.validate()

    // 验证时间逻辑
    const startTime = new Date(form.value.start_time)
    const endTime = new Date(form.value.end_time)
    
    if (endTime <= startTime) {
      ElMessage.error('结束时间必须晚于开始时间')
      return
    }

    // 验证提醒时间
    if (form.value.reminder && form.value.reminderTime) {
      const reminderTime = new Date(form.value.reminderTime)
      if (reminderTime >= startTime) {
        ElMessage.error('提醒时间必须早于开始时间')
        return
      }
    }

    loading.value = true

    // 准备提交数据
    const submitData: ScheduleCreate = {
      title: form.value.title,
      description: form.value.description,
      start_time: form.value.start_time,
      end_time: form.value.end_time,
      status: form.value.status === 'in-progress' ? 'in_progress' : form.value.status,
      priority: form.value.priority,
      is_reminder_enabled: form.value.reminder,
      reminder_minutes: form.value.reminder ? Math.floor((new Date(form.value.start_time).getTime() - new Date(form.value.reminderTime).getTime()) / 60000) : undefined
    }

    if (props.mode === 'create') {
      // 创建日程
      await scheduleStore.createNewSchedule(submitData)
    } else {
      // 更新日程
      const updateData: ScheduleUpdate = {
        description: form.value.description,
        start_time: form.value.start_time,
        end_time: form.value.end_time,
        status: form.value.status === 'in-progress' ? 'in_progress' : form.value.status,
        priority: form.value.priority,
        is_reminder_enabled: form.value.reminder,
        reminder_minutes: form.value.reminder ? Math.floor((new Date(form.value.start_time).getTime() - new Date(form.value.reminderTime).getTime()) / 60000) : undefined,
        location: form.value.location,
        notes: form.value.category
      }
      await scheduleStore.updateExistingSchedule(props.schedule!.id, updateData)
    }

    // 成功处理
    ElMessage.success(props.mode === 'create' ? '日程创建成功' : '日程更新成功')
    emit('success')
    handleClose()
  } catch (error) {
    console.error('提交表单失败:', error)
    if (error !== 'cancel') {
      ElMessage.error('操作失败，请重试')
    }
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 弹窗整体样式优化 */
:deep(.el-dialog) {
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12);
  backdrop-filter: blur(10px);
}

:deep(.el-dialog__header) {
  padding: 24px 24px 16px;
  border-bottom: 1px solid var(--el-border-color-light);
  background: linear-gradient(135deg, var(--el-color-primary-light-9) 0%, var(--el-bg-color) 100%);
  border-radius: 12px 12px 0 0;
}

:deep(.el-dialog__title) {
  font-size: 18px;
  font-weight: 600;
  color: var(--el-text-color-primary);
  letter-spacing: 0.5px;
}

:deep(.el-dialog__body) {
  padding: 24px;
  background-color: var(--el-bg-color);
}

:deep(.el-dialog__footer) {
  padding: 16px 24px 24px;
  background-color: var(--el-bg-color);
  border-radius: 0 0 12px 12px;
}

/* 表单样式优化 */
:deep(.el-form) {
  max-width: 100%;
}

:deep(.el-form-item) {
  margin-bottom: 20px;
  transition: all 0.3s ease;
}

:deep(.el-form-item:hover) {
  transform: translateY(-1px);
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: var(--el-text-color-regular);
  font-size: 14px;
  line-height: 1.6;
  padding-bottom: 8px;
}

:deep(.el-form-item__content) {
  position: relative;
}

/* 输入框样式优化 */
:deep(.el-input__wrapper) {
  border-radius: 8px;
  border: 1px solid var(--el-border-color);
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}

:deep(.el-input__wrapper:hover) {
  border-color: var(--el-color-primary);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
}

:deep(.el-input__wrapper.is-focus) {
  border-color: var(--el-color-primary);
  box-shadow: 0 0 0 3px rgba(var(--el-color-primary-rgb), 0.1);
}

:deep(.el-input__inner) {
  font-size: 14px;
  color: var(--el-text-color-primary);
  transition: all 0.3s ease;
}

/* 文本域样式优化 */
:deep(.el-textarea__inner) {
  border-radius: 8px;
  border: 1px solid var(--el-border-color);
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  resize: vertical;
  min-height: 80px;
}

:deep(.el-textarea__inner:hover) {
  border-color: var(--el-color-primary);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
}

:deep(.el-textarea__inner:focus) {
  border-color: var(--el-color-primary);
  box-shadow: 0 0 0 3px rgba(var(--el-color-primary-rgb), 0.1);
}

/* 选择器样式优化 */
:deep(.el-select) {
  width: 100%;
}

:deep(.el-select .el-input__wrapper) {
  border-radius: 8px;
  border: 1px solid var(--el-border-color);
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}

:deep(.el-select .el-input__wrapper:hover) {
  border-color: var(--el-color-primary);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
}

:deep(.el-select .el-input__wrapper.is-focus) {
  border-color: var(--el-color-primary);
  box-shadow: 0 0 0 3px rgba(var(--el-color-primary-rgb), 0.1);
}

/* 日期选择器样式优化 */
:deep(.el-date-editor) {
  width: 100%;
}

:deep(.el-date-editor .el-input__wrapper) {
  border-radius: 8px;
  border: 1px solid var(--el-border-color);
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}

:deep(.el-date-editor .el-input__wrapper:hover) {
  border-color: var(--el-color-primary);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
}

:deep(.el-date-editor .el-input__wrapper.is-focus) {
  border-color: var(--el-color-primary);
  box-shadow: 0 0 0 3px rgba(var(--el-color-primary-rgb), 0.1);
}

/* 单选框组样式优化 */
:deep(.el-radio-group) {
  display: flex;
  gap: 16px;
  flex-wrap: wrap;
}

:deep(.el-radio) {
  margin-right: 0;
  margin-bottom: 0;
}

:deep(.el-radio__label) {
  font-weight: 500;
  color: var(--el-text-color-regular);
  padding: 8px 16px;
  border-radius: 20px;
  transition: all 0.3s ease;
}

:deep(.el-radio__input.is-checked + .el-radio__label) {
  color: var(--el-color-primary);
  background-color: rgba(var(--el-color-primary-rgb), 0.1);
}

/* 开关样式优化 */
:deep(.el-switch) {
  margin-top: 8px;
}

:deep(.el-switch__core) {
  border-radius: 12px;
  border: 1px solid var(--el-border-color);
  transition: all 0.3s ease;
}

:deep(.el-switch.is-checked .el-switch__core) {
  border-color: var(--el-color-primary);
  background-color: var(--el-color-primary);
}

/* 按钮样式优化 */
.dialog-footer .el-button {
  border-radius: 8px;
  font-weight: 500;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.dialog-footer .el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
}

.dialog-footer .el-button:active {
  transform: translateY(0);
}

.dialog-footer .el-button--default {
  border: 1px solid var(--el-border-color);
  color: var(--el-text-color-regular);
  background-color: var(--el-bg-color);
}

.dialog-footer .el-button--default:hover {
  border-color: var(--el-color-primary);
  color: var(--el-color-primary);
  background-color: rgba(var(--el-color-primary-rgb), 0.05);
}

.dialog-footer .el-button--primary {
  background: linear-gradient(135deg, var(--el-color-primary) 0%, var(--el-color-primary-light-3) 100%);
  border: none;
  color: white;
}

.dialog-footer .el-button--primary:hover {
  background: linear-gradient(135deg, var(--el-color-primary-light-3) 0%, var(--el-color-primary) 100%);
  box-shadow: 0 6px 20px rgba(var(--el-color-primary-rgb), 0.3);
}

/* 字数统计样式优化 */
:deep(.el-input__count) {
  font-size: 12px;
  color: var(--el-text-color-placeholder);
  bottom: 2px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  :deep(.el-dialog) {
    width: 92% !important;
    margin: 0 !important;
    border-radius: 0 !important;
    max-height: 100vh;
    display: flex;
    flex-direction: column;
  }
  
  :deep(.el-dialog__header) {
    padding: 20px 20px 12px;
    border-radius: 0;
  }
  
  :deep(.el-dialog__title) {
    font-size: 16px;
  }
  
  :deep(.el-dialog__body) {
    padding: 16px 20px;
    max-height: 60vh;
    overflow-y: auto;
    flex: 1;
  }
  
  :deep(.el-dialog__footer) {
    padding: 12px 20px 20px;
    border-radius: 0;
    border-top: 1px solid var(--el-border-color);
  }
  
  :deep(.el-form-item__label) {
    width: 80px !important;
    font-size: 13px;
    padding-bottom: 4px;
  }
  
  :deep(.el-form-item) {
    margin-bottom: 16px;
  }
  
  :deep(.el-input__inner),
  :deep(.el-textarea__inner) {
    font-size: 13px;
  }
  
  .dialog-footer {
    flex-direction: column-reverse;
    gap: 10px;
  }
  
  .dialog-footer .el-button {
    width: 100%;
    height: 48px;
    font-size: 14px;
  }
  
  :deep(.el-radio-group) {
    gap: 12px;
  }
  
  :deep(.el-radio__label) {
    padding: 6px 12px;
    font-size: 13px;
  }
}

@media (max-width: 480px) {
  :deep(.el-dialog) {
    width: 96% !important;
  }
  
  :deep(.el-dialog__header) {
    padding: 16px 16px 12px;
  }
  
  :deep(.el-dialog__title) {
    font-size: 15px;
  }
  
  :deep(.el-dialog__body) {
    padding: 12px 16px;
    max-height: 65vh;
  }
  
  :deep(.el-dialog__footer) {
    padding: 12px 16px 16px;
  }
  
  :deep(.el-form-item__label) {
    width: 70px !important;
    font-size: 12px;
  }
  
  :deep(.el-form-item) {
    margin-bottom: 14px;
  }
  
  :deep(.el-input__inner),
  :deep(.el-textarea__inner) {
    font-size: 12px;
  }
  
  .dialog-footer .el-button {
    height: 44px;
    font-size: 13px;
  }
  
  :deep(.el-radio-group) {
    gap: 8px;
  }
  
  :deep(.el-radio__label) {
    padding: 4px 8px;
    font-size: 12px;
  }
}

/* 深色模式优化 */
@media (prefers-color-scheme: dark) {
  :deep(.el-dialog) {
    background-color: var(--el-bg-color-overlay);
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.32);
  }
  
  :deep(.el-dialog__header) {
    background: linear-gradient(135deg, rgba(var(--el-color-primary-rgb), 0.1) 0%, var(--el-bg-color-overlay) 100%);
  }
  
  :deep(.el-input__wrapper) {
    background-color: var(--el-bg-color-overlay);
    border-color: var(--el-border-color-darker);
  }
  
  :deep(.el-input__wrapper:hover) {
    border-color: var(--el-color-primary);
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.2);
  }
  
  :deep(.el-textarea__inner) {
    background-color: var(--el-bg-color-overlay);
    border-color: var(--el-border-color-darker);
  }
  
  :deep(.el-textarea__inner:hover) {
    border-color: var(--el-color-primary);
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.2);
  }
  
  :deep(.el-select .el-input__wrapper) {
    background-color: var(--el-bg-color-overlay);
    border-color: var(--el-border-color-darker);
  }
  
  :deep(.el-date-editor .el-input__wrapper) {
    background-color: var(--el-bg-color-overlay);
    border-color: var(--el-border-color-darker);
  }
}
</style>
